iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0

在先前我們有介紹過Component,今天我們將要更深入了解Component的世界。
在大多數使用表單的情況下,我們使用的Component都是controlled component,而使用controlled component的資料會被React component所處理,另一個選擇是可以使用Uncontrolled Component,那這時候處理的就不會是React component,而是由DOM負責。

controlled component
受控組件
使用controlled component輸入表單元素是由 react 本身而不是 DOM 處理。在這種情況下,可變狀態保存在 state 屬性中,並且只能使用 setState() 方法進行更新。
使用controlled component的好處在於在每次發生onChange事件時傳遞給它們的數據,然後會將數據保存並使用 setState() 方法進行更新,這樣可以使元素和數據更好的被控制。

Uncontrolled Component
不受控組件
表單數據由 DOM 本身處理,如果要編寫一個Uncontrolled Component就要使用到ref從 DOM 取得表單的資料,就不需要在每次更新時都要重新寫一個event handler。

controlled component vs Uncontrolled Component
受控 不受控
受組件狀態的控制 受 DOM 控制
可預測的 因為不受控,數據有可能丟失
無維護內部狀態 不須使用event handler維護狀態
使用props 使用refs
對於表單更好的控制 不好控制

參考文章:
https://www.javatpoint.com/react-controlled-vs-uncontrolled-component
https://www.geeksforgeeks.org/controlled-vs-uncontrolled-components-in-reactjs/


上一篇
[DAY18]在React中使用CSS!
下一篇
[DAY20]ReactDOMServer是甚麼?
系列文
進階前端網頁設計-初心者的30天React學習及應用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言